const gulp = require("gulp")
const htmlmin = require("gulp-htmlmin")
const cleanCss = require("gulp-clean-css")
const autoprefixer = require("gulp-autoprefixer")
const babel = require("gulp-babel")
const uglify = require("gulp-uglify")
const connect  = require("gulp-connect")
const sass = require("gulp-sass")
const del = require("del")
const proxy = require("http-proxy-middleware")

const path = {
    html:{
        src:"src/**/*.html",
        dest:"dist"
    },
    css:{
        src:"src/css/**/*.scss",
        dest:"dist/css"
    },
    js:{
        src:"src/js/**/*.js",
        dest:"dist/js"
    },
    img:{
        src:"src/images/*",
        dest:"dist/images"
    },
    libs:{
        src:"src/libs/**/*",
        dest:"dist/libs"
    }
    
}
const delDist = () => del("dist")
const html = () =>{
    console.log(path)
    return gulp.src(path.html.src)
    .pipe(htmlmin({
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input checked />
          removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
          removeScriptTypeAttributes: false,//删除<script>的type="text/javascript"
          removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
          minifyJS: true,//压缩页面JS
          minifyCSS: true//压缩页面CSS
    }))
    .pipe(gulp.dest(path.html.dest))
    .pipe(connect.reload())
}
const css =() => {
    return gulp.src(path.css.src)
    .pipe(sass())
    .pipe(autoprefixer())
    .pipe(cleanCss())
    .pipe(gulp.dest(path.css.dest))
    .pipe(connect.reload())
}
const js = () => {
    return gulp.src(path.js.src)
        .pipe(babel({
            presets: ['@babel/env']
        }))
        .pipe(uglify())
        .pipe(gulp.dest(path.js.dest))
        .pipe(connect.reload())
}
const img = () =>{
    return gulp.src(path.img.src)
    .pipe(gulp.dest(path.img.dest))
}
const libs = () => {
    return gulp.src(path.libs.src)
    .pipe(gulp.dest(path.libs.dest))
    .pipe(connect.reload())
}
const server = () =>{
    connect.server({
    root:"dist",
    port:4747,
    livereload:true,
    middleware:function () {
      return[
          proxy.createProxyMiddleware("/api",{
              target:"http://localhost",
              changeOrigin:true
          })
      ]  
    }     
    })
}
const ico = () => gulp.src('src/favicon.ico').pipe(gulp.dest('dist'))

const watch = () =>{
    gulp.watch(path.html.src,html)
    gulp.watch(path.css.src,css)
    gulp.watch(path.js.src,js) 
    gulp.watch(path.libs.src,libs)
}

module.exports.default = gulp.series(delDist, gulp.parallel(html, js, css, ico, img, libs, watch, server))